import router from '@/router'
import child from '@/router/child.js'
import store from '@/store'
import NProgress from 'nprogress' // Progress 进度条
import 'nprogress/nprogress.css' // Progress 进度条样式
import { getMenu } from '@/utils/auth' // 验权
import { getToken } from '@/utils/auth'
// import { loadComponent } from '@/utils'
export function parseUrl(url) {
  if (Object.prototype.toString.call(url) !== '[object String]') {
    return { url: '', isExternal: false }
  }
  if (/^https?:\/\//.test(url)) {
    return {
      url: '/iframe/' + encodeURIComponent(url),
      isExternal: true
    }
  } else if (url.substring(0, 8) === '/iframe/') {
    return {
      url,
      isExternal: true
    }
  } else if (url.charAt(0) === '/') {
    return {
      url: url.toLocaleLowerCase(),
      isExternal: false
    }
  } else {
    return { url: '', isExternal: false }
  }
}
const toRoute = function(item, pids, route) {
  const { url, isExternal } = parseUrl(item.nodeType !== 3 && item.url)
  if (url) {
    item.pids = pids

    route.push({
      path: `${url}`,
      component: isExternal
        ? () => import('@/views/iframeTemplateEmpty.vue')
        : () => import(`@/views${url}/index.js`),
      name: pids.concat(item.id).join('-'),
      icon: '',
      meta: Object.assign(item, { pids, url: `${url}` }),
      noDropdown: true
    })

    if (child.hasOwnProperty(url)) {
      [].concat(child[url]).map((c, i) => {
        const id = `${item.id}.${i}`
        c.meta = Object.assign(
          {
            children: item.children || [],
            id,
            pids: pids.concat(item.id),
            // hideMenu: true,
            addTag: false,
            text: c.name
          },
          c.meta || {}
        )
        route.push(c)
      })
    }
  }
  if (item.children && item.children.length) {
    for (let i = 0, len = item.children.length; i < len; i++) {
      toRoute(item.children[i], [...pids, item.id], route)
    }
  }
}

export function menuToRoute(menu) {
  const route = {
    path: '/',
    // component: loadComponent('layout/index.vue'),
    component: () => import('@/layout/index.vue'),
    chunkName: 'views/index',
    children: [],
    hidden: true
  }
  menu.forEach(item => {
    toRoute(item, [], route.children)
  })
  return [route]
}
export function addRoutes(menu) {
  router.addRoutes(menuToRoute(menu))
}

export function filterMenu(item) {
  return !/example/i.test(item.id)
}

const menu = getMenu()

if (menu) {
  router.addRoutes(menuToRoute(menu))
}

router.beforeEach((to, from, next) => {
  NProgress.start()
  if (getToken()) {
    store.commit('SET_TOKEN', getToken())
  }
  document.title = store.getters.systemName || '权限管理平台'
  next()
})

router.afterEach(() => {
  NProgress.done() // 结束Progress
})
